home *** CD-ROM | disk | FTP | other *** search
- Path: newshub.cts.com!RIP
- From: ripr@cts.com (William Rinehart)
- Newsgroups: comp.lang.c
- Subject: Help using qsort to sort pointers to a structure
- Date: Sun, 28 Jan 96 16:39:21 GMT
- Organization: CTSNET
- Message-ID: <4eg8rp$2oo_001@news2.cts.com>
- NNTP-Posting-Host: ripr.cts.com
-
- I'm trying to use qsort to sort the "names" elements in the structure called "data".
- The code below compiles with no errors or warnings, but GPFs (segmentation fault on a
- UNIX box) when it is run. Apparently the fault is in the strcmp call. I don't see
- what's wrong with it. Can anyone help?
-
- Thanks!
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- struct alpha {
- char names[20];
- };
-
- struct alpha data[4]=
- { {"bbb"}, {"aaa"}, {"ddd"}, {"ccc"} };
-
- int compname(const void *arg1, const void *arg2);
-
- int
- main(void)
- {
-
- int i;
-
- for (i=0; i < 4; i++) /* print pre-sort list */
- printf("%s\n",data[i].names);
-
- qsort((void *)data, (size_t)4, sizeof(struct alpha *), compname);
-
- for (i=0; i < 4; i++) /* print sorted list */
- printf("%s\n",i, data[i].names);
- return(0);
- }
-
- int
- compname(const void *arg1, const void *arg2)
- {
- /* cast arg1 and arg2 as pointers to pointers, then derefence
- so that strcmp gets "regular" pointer as arguments */
- return (strcmp((*(struct alpha**)arg1)->names, (*(struct alpha**)arg2)->names));
- }
-